<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar fixed placeholder title="购物车案例" />

    <!-- 商品列表区域 -->
    <van-cell-group style="margin-bottom:50px">
      <van-cell v-for="item in list" :key="item.id">
        <template>
          <div class="goods-item">
            <!-- 左侧checkbox外加图片 -->
            <van-checkbox v-model="item.goods_state" shape="square">
              <van-image
                width="120"
                height="120"
                :src="item.goods_img"
                fit="cover"
                radius="10"
              />
            </van-checkbox>
            <!-- 右侧div -->
            <div class="info-box">
              <div class="title">{{ item.goods_name }}</div>
              <div class="price-box">
                <span class="price">￥ {{ item.goods_price }}</span>
                <van-stepper
                  v-model="item.goods_count"
                  theme="round"
                  button-size="22"
                  disable-input
                />
              </div>
            </div>
          </div>
        </template>
      </van-cell>
    </van-cell-group>

    <!-- 提交订单栏 -->
    <van-submit-bar :price="total" :button-text="totalCount">
      <van-checkbox v-model="checkAll">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      checked: true,
      value: 1,
      list: [],
    };
  },

  async created() {
    const res = await axios({
      url: "https://www.escook.cn/api/cart",
    });

    this.list = res.data.list;
  },
  // 计算属性
  computed: {

    total () {

      // 累加
      let sum = 0
      // 遍历数组
      this.list.forEach(v => {

        // 只能累加选中的商品
        if (v.goods_state) {
          // 单价*数量 再累加起来
          sum += v.goods_price * v.goods_count
        }
      })

      return sum * 100
    },

    // 全选
    checkAll: {

      get () {
        // 依赖数组，看有没有全部选中
        return this.list.every(v => v.goods_state)
      },

      set (val) {

        this.list.forEach(v => v.goods_state = val)
      }
    },

    totalCount () {

      // 累加选中的数量
      let count = 0
      this.list.forEach(v => {

        if (v.goods_state) {
          count += v.goods_count
        }
      })

      return `结算(${count}件)`
    }
  }
};
</script>

<style>
.goods-item {
  display: flex;
}

.info-box {
  flex: 1;
  margin-left: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.title {
  font-weight: 700;
}

.price {
  color: red;
}

.price-box {
  display: flex;
  justify-content: space-between;
}
</style>